package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.dto.HotSearchAddDTO;
import cn.com.dcsgo.dto.HotSearchQueryDTO;
import cn.com.dcsgo.dto.HotSearchUpdateDTO;
import cn.com.dcsgo.dto.PageDTO;
import cn.com.dcsgo.exception.BusinessException;
import cn.com.dcsgo.utils.AuthUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.dcsgo.domain.HotSearch;
import cn.com.dcsgo.service.HotSearchService;
import cn.com.dcsgo.mapper.HotSearchMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 针对表【hot_search(热搜)】的数据库操作Service实现
 *
 * @author Dcsgo
 * @since 2025-10-26 13:09:56
 */
@Service
public class HotSearchServiceImpl extends ServiceImpl<HotSearchMapper, HotSearch>
        implements HotSearchService {

    @Override
    public Page<HotSearch> getPage(PageDTO pageDTO, HotSearchQueryDTO hotSearchQueryDTO) {
        Long shopId = AuthUtil.getShopId();
        Page<HotSearch> page = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        String content = hotSearchQueryDTO.getContent();
        String title = hotSearchQueryDTO.getTitle();
        Integer status = hotSearchQueryDTO.getStatus();
        return baseMapper.selectPage(page,
                new LambdaQueryWrapper<HotSearch>()
                        .eq(status != null, HotSearch::getStatus, status)
                        //shopId==0表示是全局热搜，shopId==1是超级店铺
                        .in(shopId == null || !shopId.equals(1L), HotSearch::getShopId, 0, shopId)
                        .like(StringUtils.hasText(title), HotSearch::getTitle, title)
                        .like(StringUtils.hasText(content), HotSearch::getContent, content)
                        .orderByDesc(HotSearch::getSeq)
        );
    }

    @Override
    public boolean save(HotSearchAddDTO hotSearchAddDTO) {
        Long shopId = AuthUtil.getShopId();
        if (shopId == null) {
            throw new BusinessException("请关联店铺后再操作");
        }
        HotSearch saveData = new HotSearch();
        BeanUtil.copyProperties(hotSearchAddDTO, saveData);
        saveData.setShopId(shopId);
        if (saveData.getStatus() == null) {
            saveData.setStatus(1);
        }
        int row = baseMapper.insert(saveData);
        return row > 0;
    }

    @Override
    public boolean update(HotSearchUpdateDTO hotSearchUpdateDTO) {
        HotSearch updateData = new HotSearch();
        BeanUtil.copyProperties(hotSearchUpdateDTO, updateData);
        int row = baseMapper.updateById(updateData);
        return row > 0;
    }
}




